/*
var noticeMessage = {uname: '请输入您的姓名，汉字或字母。',
                     cellphone: '请输入您的手机号码，11位数字。',
                     mobile: '请输入您的手机号码，11位数字。',
                     vcode: '请输入您手机收到的6位数字验证码。',
                     passwd: '请填写6-16个数字、字母或特殊符号。',
                     email: '请输入您的邮箱。',
                     vpasswd: '请再次输入密码。',
                     validateCode: '请输入验证码。'}
var errorMessage = {uname: ['称呼在1-5个汉字之内。'],
                    cellphone: ['手机号码格式不正确。', '手机号码位数不正确。','该号码已被使用'],
                    mobile: ['手机号码格式不正确。', '手机号码位数不正确。','该号码已被使用'],
                    vcode: ['验证码不正确。'],
                    email: ['邮箱格式不正确。'],
                    passwd: ['密码在6-16个字符内。','密码不能全为数字。'],
                    vpasswd: ['密码和确认密码不一致。']};
*/
window.Validator = {
	config: {
		'vcodeUrl' : '/vcode/check',
		'tip_id_pre':'err_tip_',
		'rightHintHTML': '<div></div>',
		'hint_left_offset': 55,
		'hint_top_offset' :0
	},
	rules : {
		'notempty': /\S/,
		'mobile': /^1[3|4|5|8]\d{9}$/,
		'email': /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/,
		'length': function(value, param){
			var l = param.split(',');
			return value.length >= (+l[0] || 0) && value.length <= (+l[1] || Infinity);
		},
		'sameas': function(value, param){
			return $('[valid='+param +']').val() == value;
		},
		'number': /^[\d\.]+$/,
		'positive': function(value){
			if(! /^[\d\.]+$/.test(value)){
				return false;
			}
			return parseFloat(value) > 0;
		},
		/*
		'range': function(value, param){
			var l = param.split(','),
				v = parseFloat(value);
			return v > (+l[0] || 0) && v < (+l[1] || Infinity);
		},
		*/
		'maxvalue': function(value, param){
			if(! /^[\d\.]+$/.test(value)){
				return false;
			}
			return parseFloat(value) < parseFloat(param);
		},
		//vcode is private for Rong360.com .
		'vcode': function(value, param,verifypic){
			var result = true;
			$.ajax({
				url: Validator.config.vcodeUrl,
				data: {'type':param,'vcode':value},
				async: false,
				success: function(data){
					result = (data !== 'false');
				}
			});
            //验证码错误后,刷新验证码
            if(!result && verifypic){
                $('#'+verifypic).attr('src',$('#'+verifypic).attr('src')+'1');
            }
			return result;
		},
		'scode':function(value,param){
			var result = true;
			$.ajax({
				url:"/"+param+"/checkscode.html?scode="+value,
				method:'GET',
				async:false,
				success: function(data){
					result = (data !== 'false');
				}
			});
			return result;
		},
        /*临时添加做为验证订单手机验证码验证*/
        '__scode':function(value){
            var result = true;
            $.ajax({
                url:"/apply/checkScode.html?scenario=after_order&scode="+value+"&order_id="+$('#order_id_inp').val(),
                method:"GET",
                async:false,
                success:function(data){
                    result = (data !=='false')
                }
            });
            return result;
        }
	},
	initForm: function(form, requiredOnly, showFirstErrorOnly){
		form = $(form);
		$('[valid]', form).blur(function(){
			var $this = $(this);
            //add keyup-valid-len by zouyoufang, 2013-09-16,用于在输入时进行数据验证。
			if((!$this.attr('blur-valid') || $this.attr('blur-valid')!=='false')
                && (!$(this).attr('keyup-valid-len') || $(this).attr('keyup-valid-len')!=$(this).val().length || $(this).attr('blur-keyup-valid')=="true")
                ){
				Validator.validItem($this);
			}
		});
		$('[keyup-valid-len]', form).keyup(function(){
            if($(this).val().length==$(this).attr('keyup-valid-len')){
				Validator.validItem($(this));
            }else{
                Validator._clearHint($(this));
            }
        });
		$('[blur-valid=false]',form).blur(function(){
			Validator._clearHint($(this));			
		});
		Validator.limitInput();
		
		form.submit(function(evt){
			if(!Validator.validForm(form, requiredOnly, showFirstErrorOnly)){
                alert('prevented');
				evt.preventDefault();
			}
		});

	},
	validForm: function(form, requiredOnly, showFirstErrorOnly){
		form = $(form);
		var result = true;
		$( requiredOnly ? '[required]':'[valid]',form).each(function(idx, el){
			el = $(el);
			result &= Validator.validItem(el);
			if(showFirstErrorOnly && (!result) ){
				return false;
			}
		});
		return result;
	},
	validItem: function ( el ) { 
		el = $(el);
		var me = Validator,
			msgs = el.attr('valid-data'),
			style = el.attr('valid-style'),
			allResult = true;
		//跳过选填项
		if(el.attr('valid-opt') && (el.val()=='' || el.val()=='选填') ){
			Validator._clearHint(el);
			return true;
		}

		$.each(msgs.split('||'), function(idx, dataItem){
			var kv = dataItem.split('|'),
				ruleParam = kv[0].split(':'),
				msg = kv[1],
				rule = me.rules[ruleParam[0]],
				result = true;
			
			switch($.type(rule)) {
				case 'function':
					result = rule(el.val(), ruleParam[1],ruleParam[2]);
					break;
				case 'regexp':
					result = rule.test(el.val());
					break;
				default:;
			}
			if(!result){
				me.showError(el, msg,style);
				allResult = false;
				return false;
			}
		});
		if(allResult){
			me.showRight(el);
		}
		return allResult;
	},
	showError: function(el, msg, style){
		//'<div style="display: inline" class="input-err validate-hint"><em></em><var>' + msg + '</var></div>'
        if(style==2){
            Validator._showHint(el, '<div class="validate-hint clearfix"><div class="valid-error">&nbsp;</div></div>');
        }else{
            Validator._showHint(el, '<div class="validate-hint clearfix"><div class="valid-hint-arrow"></div><div class="valid-hint-text">@msg</div></div>'.replace('@msg',msg) );
        }
	},
	showRight: function(el){
		Validator._showHint(el, Validator.config.rightHintHTML);
	},
	clearHint: function(){
		$('.validate-hint').remove();
	},
	_clearHint: function(el){
		el = $(el);
		var id = Validator.config.tip_id_pre + el.attr('valid');
		$('#' + id).remove();
	},

	_showHint: function (el, html){
		el = $(el);
		//add by twy
		if(el.is(':hidden')){
			return;
		}
		var offset = el.offset(),
			id = Validator.config.tip_id_pre + el.attr('valid'),
			hint,
			hint_left_offset = el.attr('hint-left-offset') ? parseInt(el.attr('hint-left-offset')) : 0;
		$('#' + id).remove();
		if(!html) return;
		hint = $(html)
			.attr('id', id)
			.appendTo(document.body);
		hint.css({position:'absolute',
			zIndex:199,
			top:offset.top + (el.outerHeight() - hint.height())/2 +Validator.config.hint_top_offset, 
			left:offset.left + $(el).outerWidth() + Validator.config.hint_left_offset + hint_left_offset});
	},

	limitInput: function(){
		$('input[cate="num"]').keydown(function(evt){
			var keyCode = evt.keyCode;
			if(keyCode == 229){//一些中文输入法表示输入为中文字符,无法检测真实字符,忽略
				return;
			}
			if(!((keyCode >= 48 && keyCode <= 57) || 
				 (keyCode >= 96 && keyCode <= 105)) &&
				keyCode != 190 && keyCode != 8 &&
				keyCode != 37 && keyCode != 39 &&
				keyCode != 9 && keyCode != 110 &&
				keyCode != 46 
				){
				evt.preventDefault();
				return;
			}
			if ((keyCode == 190 || keyCode == 110) && 
				$(this).val().indexOf('.') > -1){
				evt.preventDefault();
			}
		});

	},

	addRule: function(ruleName, rule){
		Validator.rules[ruleName] = rule;
	}
}
